using DevExpress.Xpo;
using PostSharp.CodeModel;
using PostSharp.Laos.Weaver;

namespace XpoOneWayMultiAssociationWeaver
{
   public class AssociationAttributeWeaver : TypeLevelAspectWeaver
   {
      #region Constructors

      public AssociationAttributeWeaver(string propertyName, string associationName)
      {
         PropertyName = propertyName;
         AssociationName = associationName;
      }

      #endregion

      #region Fields

      public readonly string AssociationName;
      public readonly string PropertyName;

      private PropertyDeclaration linkProperty;

      #endregion

      #region Methods

      /// <summary>
      /// Adds an <see cref="AssociationAttribute"/> to the one-way multi property.
      /// </summary>
      public override void Implement()
      {
         var module = Task.Project.Module;
         var attribute = Utils.CreateAssociationAttribute(module, AssociationName);
         LinkProperty.CustomAttributes.Add(attribute);
      }

      #endregion

      #region Properties

      /// <summary>
      /// The link property.
      /// </summary>
      /// <value>The link property.</value>
      private PropertyDeclaration LinkProperty
      {
         get
         {
            if (linkProperty == null)
            {
               foreach (var property in ((TypeDefDeclaration) TargetType).Properties)
               {
                  if (property.Name == PropertyName)
                  {
                     linkProperty = property;
                  }
               }
            }
            return linkProperty;
         }
      }

      #endregion
   }
}